package us.wili.dev.netty.service.impl;

import com.corundumstudio.socketio.SocketIOClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.wili.dev.dao.mapper.common.GroupMsgMapper;
import us.wili.dev.model.base.BaseUser;
import us.wili.dev.model.constants.NettyReqEnum;
import us.wili.dev.model.entity.GroupChat;
import us.wili.dev.model.entity.GroupMsg;
import us.wili.dev.model.entity.User;
import us.wili.dev.netty.model.GameResponseDto;
import us.wili.dev.netty.service.NettyGroupChatService;
import us.wili.dev.netty.service.NettyGroupMsgService;
import us.wili.dev.netty.service.UserService;
import us.wili.dev.service.BaseUserService;
import us.wili.dev.service.impl.BaseGroupMsgServiceImpl;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NettyGroupMsgServiceImpl extends BaseGroupMsgServiceImpl implements NettyGroupMsgService {

    @Resource
    private GroupMsgMapper groupMsgMapper;

    @Autowired
    private NettyGroupChatService groupChatService;
    @Autowired
    private UserService userService;

    @Override
    public GameResponseDto handlerOffLine(Long clientID,SocketIOClient client) {
        User user = userService.findByUserID(Long.valueOf(clientID));
        if (user!=null){
            List<GroupChat> groupIDs = groupChatService.listByUserID(user.getId());
            if (groupIDs.size()>0) {
                List<GroupMsg> groupMsgList = listByGroupIDs(groupIDs.stream().map(GroupChat::getGroupid).collect(Collectors.toList())
                        ,user.getUpdatedAt());
                GameResponseDto gameResponseDto = new GameResponseDto();
                gameResponseDto.setCmd(NettyReqEnum.OFFLINE_GROUP_MSG.getID());
                gameResponseDto.setRequestId("");
                gameResponseDto.setData(groupMsgList);
                client.sendEvent("message_event",gameResponseDto);
            }
        }
        return null;
    }

    @Override
    public void saveMSG(GroupMsg groupMsg) {
        if (groupMsg!=null)
        {
            groupMsgMapper.insert(groupMsg);
        }
    }
}
